<?php

namespace app\admin\model;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * Goods
 * @controllerUrl 'goods'
 * @property int stock
 * @property int commission1
 * @property number commission2
 * @property number commission3
 * @property string goods_name
 * @property array coupon_ids
 * @property int integral
 * @property int sales
 */
class Goods extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $hidden = ['attr_keys'];

    protected $type = [
        'deletetime' => 'timestamp:Y-m-d H:i:s',
    ];


    public function getCategoryIdAttr($value, $row)
    {
        return !$value ? '' : $value;
    }

    public function getSliderImagesAttr($value, $row)
    {
        if ($value == '') {
            return [];
        }
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setSliderImagesAttr($value, $row)
    {
        if ($value && is_array($value)) {
            return implode(',', $value);
        }
        return $value ? $value : '';
    }

    public function getCouponIdsAttr($value, $row)
    {
        if ($value == '') {
            return [];
        }
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setCouponIdsAttr($value, $row)
    {
        if ($value && is_array($value)) {
            return implode(',', $value);
        }
        return $value ? $value : '';
    }

    public function getContentImagesAttr($value, $row)
    {
        if ($value == '') {
            return [];
        }
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setContentImagesAttr($value, $row)
    {
        if ($value && is_array($value)) {
            return implode(',', $value);
        }
        return $value ? $value : '';
    }

    public function setBestSwitchAttr($value, $row)
    {
        return $value ? '1' : '0';
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class, 'coupon_ids', 'id');
    }

    public function attr()
    {
        return $this
            ->hasMany(GoodsAttr::class, 'goods_id', 'id')
            ->hidden(['goods_id', 'createtime', 'delete_time']);
    }
}